package com.kjlink.widget.monitoring.entity;

import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.time.LocalDateTime;

/**
 * 描述:
 *
 * @author Vic.xu
 * @since 2025-08-05 10:35
 */
@Getter
@Setter
@Entity
@Table(name = "T_MONITOR_EVENT_BATCH")
public class MonitorEventBatch extends BaseEntity{



    /**
     *  批次唯一标识
     */
    @Column(name = "BATCH_NO", length = 64, nullable = false, unique = true)
    private String batchNo;

    /**
     *  事件类型
     */
    @Column(name = "EVENT_TYPE", length = 32, nullable = false)
    private String eventType;

    /**
     * 事件 初个业务id
     */
    @Column(name = "BUSINESS_ID", length = 64, nullable = false)
    private String businessId;

    /**
     *  批次内首个事件id
     */
    @Column(name = "FIRST_EVENT_ID", length = 32, nullable = false)
    private String firstEventId;

    /**
     *  批次内首个事件发生时间
     */
    @Column(name = "FIRST_OCCUR_TIME", nullable = false)
    private LocalDateTime firstOccurTime;

    /**
     * 批次内最后一个事件发生时间
     */
    @Column(name = "LAST_OCCUR_TIME", nullable = false)
    private LocalDateTime lastOccurTime;

    /**
     * 当前批次的戒指时间
     */
    @Column(name = "END_TIME", nullable = false)
    private LocalDateTime endTime;

    /**
     *  批次内事件总次数
     */
    @Column(name = "EVENT_COUNT", nullable = false)
    private Integer eventCount = 0;

    /**
     * 批次内最新事件数据
     */
    @Column(name = "LATEST_DATA", length = 3000)
    private String latestData;

    /**
     * 批次处理时间
     */
    @Column(name = "PROCESS_TIME")
    private LocalDateTime processTime;

    /**
     * 批次处理状态
     */
    @Column(name = "STATUS", length = 16)
    @Enumerated(EnumType.STRING)
    private BatchStatus status = BatchStatus.initial;

    /**
     * 遗留压缩 : 上一次发送失败的批次, 保留到 压缩周期内
     * 最靠近本次的上一个批次, 且是失败的, 且批次的结束时间和当前时间的差距不超过 压缩周期
     */
    @Column(name = "LEGACY_BATCH_FROM", length = 32)
    private String legacyBatchFrom;
    /**
     * 遗留批 批次的事件次数
     */
    @Column(name = "LEGACY_BATCH_COUNT")
    private Integer legacyBatchCount = 0;

    /**
     * 批次内首个事件:  手动查询
     */
    @Transient
    private MonitorRawEvent firstRawEvent;

    /**
     * 批次状态枚举
     */
    public enum BatchStatus {
        // 待处理，
        initial,
        // success
        success,
        fail,
        // 过期
        expire;
    }

    /**
     * 获取批次内事件总数: 批次内事件数 + 遗留批次事件数
     */
    public int getCount(){
        if (eventCount == null) {
            return legacyBatchCount == null ? 1 : legacyBatchCount;
        }
        if (legacyBatchCount == null) {
            return eventCount == null ? 1 : eventCount;
        }
        return eventCount + legacyBatchCount;
    }
}